package cn.harry.cabinet.utils

import android.util.Log
import java.net.NetworkInterface

/**
 * IP地址工具类
 */
object IpUtil {
    private const val TAG = "IpUtil"

    /**
     * 获取本地IP地址
     * @return 本地IP地址，如果获取失败则返回null
     */
    fun getLocalIpAddress(): String? {
        try {
            val networkInterfaces = NetworkInterface.getNetworkInterfaces()
            while (networkInterfaces.hasMoreElements()) {
                val networkInterface = networkInterfaces.nextElement()
                
                // 跳过回环接口、虚拟接口等
                if (networkInterface.isLoopback || !networkInterface.isUp) {
                    continue
                }
                
                val addresses = networkInterface.inetAddresses
                while (addresses.hasMoreElements()) {
                    val address = addresses.nextElement()
                    
                    // 跳过IPv6地址和回环地址
                    if (address.isLoopbackAddress || address.hostAddress?.contains(":") == true) {
                        continue
                    }
                    
                    val ip = address.hostAddress
//                    Log.d(TAG, "找到IP地址: $ip")
                    
                    // 优先返回非保留地址（通常是外网地址）
                    if (ip != null && !isReservedAddress(ip)) {
                        return ip
                    }
                }
            }
            
            // 如果没有找到非保留地址，再次遍历查找任何可用的IPv4地址
            val networkInterfaces2 = NetworkInterface.getNetworkInterfaces()
            while (networkInterfaces2.hasMoreElements()) {
                val networkInterface = networkInterfaces2.nextElement()
                if (!networkInterface.isUp) continue
                
                val addresses = networkInterface.inetAddresses
                while (addresses.hasMoreElements()) {
                    val address = addresses.nextElement()
                    if (address.isLoopbackAddress || address.hostAddress?.contains(":") == true) {
                        continue
                    }
                    
                    return address.hostAddress
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "获取IP地址失败: ${e.message}")
        }
        
        return null
    }
    
    /**
     * 判断IP地址是否为保留地址
     * @param ip IP地址
     * @return 如果是保留地址则返回true，否则返回false
     */
    private fun isReservedAddress(ip: String): Boolean {
        return ip.startsWith("10.") || 
               ip.startsWith("172.16.") || 
               ip.startsWith("192.168.") || 
               ip.startsWith("127.")
    }
}